<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\AdminUser\Action\Admin\Index;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Tenant\Contract\TenantContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\AdminUser\Contract\AdminUserContract;
use MoChat\Plugin\AdminUser\Middleware\AdminAuthMiddleware;
use MoChat\Plugin\AdminUser\Middleware\PermissionMiddleware;

/**
 * 超级管理员-系统首页.
 *
 * Class SysIndex.
 * @Controller
 */
class SysIndex extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var TenantContract
     */
    protected $tenantService;

    /**
     * @Inject
     * @var AdminUserContract
     */
    protected $adminUserService;

    /**
     * @RequestMapping(path="/admin/adminUser/sysIndex", methods="get")
     * @Middlewares({
     *     @Middleware(AdminAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        // 参数验证
        $this->validated($this->request->all());
        $adminUser = user();
        // 自营注册用户：指当前登录用户名下的所有租户数量；
        $totalTenantNum = $this->tenantService->countTenantByOwnerId([$adminUser['id']], '', '');
        // 自营付费租户：指当前登录用户名下的所有已付费的租户；(会有0员体验套餐，那个不算)；
        $payTenantNum = $this->tenantService->countTenantByOwnerId([$adminUser['id']], '', '', 1);
        // 渠道/代理商：指当前用户发展的代理商数量；
        $agent = $this->adminUserService->getAdminUserByParentId($adminUser['id'], 1, ['id']);
        // 渠道/代理租户：指当前用户发展的代理商名下的所有租户数量。
        $agentTenantNum = 0;
        if (! empty($agent)) {
            $agentTenantNum = $this->tenantService->countTenantByOwnerId(array_column($agent, 'id'), '', '');
        }
        $user = $this->adminUserService->getAdminUserById($adminUser['id'], ['wallet_balance']);
        return [
            'totalTenantNum' => $totalTenantNum,
            'payTenantNum' => $payTenantNum,
            'agentNum' => count($agent),
            'agentTenantNum' => $agentTenantNum,
            'walletBalance' => $user['walletBalance'],
        ];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }
}
